<template>
  <div class="right">
    <div class="live-stream">
      <div class="tab">
        <button class="live-button">直播</button>
      </div>

      <div class="ranking-tabs">
        <span class="active-tab">贡献日榜</span>
        <span>贡献周榜</span>
      </div>
      <div class="ranking-list">
        <div class="ranking-item">
          <img src="@/assets/icons/live-detail/1.webp" alt="2nd" class="ranking-badge" />
          <span class="player-name">虚位以待 </span>
          <span class="points"></span>
        </div>
        <div class="ranking-item">
          <img src="@/assets/icons/live-detail/2.webp" alt="2nd" class="ranking-badge" />
          <span class="player-name">虚位以待 </span>
          <span class="points"></span>
        </div>
        <div class="ranking-item">
          <img src="@/assets/icons/live-detail/3.webp" alt="2nd" class="ranking-badge" />
          <span class="player-name">虚位以待 </span>
          <span class="points"></span>
        </div>
      </div>
      <div class="activity">
        <img src="@/assets/icons/live-detail/speaker.webp" />
        <span class="txt">任何群、广告均为诈骗，违规者封号处理 </span>
      </div>
      <div class="message-container" ref="messageContainer">
        <div class="vip-list">
          <div class="vip-item" v-for="(res, index) in messageList" :key="res.id">
            <img src="@/assets/icons/live-detail/chat-level0.webp" alt="VIP1" class="vip-badge" />
            <div>
              <span class="nickname">{{ res?.nickname }}:</span>
              <span class="text">{{ res?.content }}</span>
            </div>
          </div>
        </div>
      </div>

      <div class="join-list">
        <span class="nickname">{{ joinList.data.nickname }}</span>
        <span class="text">{{ joinList.data.content }}</span>
      </div>
      <div class="comment-section">
        <div class="comment-input">
          <div class="isNotLogin" v-if="!isLogin">
            <span class="login_btn" @click="login">登陆</span>
            <span>参与与主播一起聊球</span>
          </div>
          <div class="isLogin" v-if="isLogin">
            <input
              type="text"
              placeholder="说点有爱的评论~"
              v-model="msg"
              @keydown.enter="sendMsg"
            />
            <button class="send-button" @click="sendMsg">发送</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted, onUnmounted, nextTick, defineProps } from 'vue'
import { getDQRongImLibToken } from '@/api/user'
import * as RongIMLib from '@rongcloud/imlib-next'
import { useRouter } from 'vue-router'
import { AppConfigStore } from '@/stores/app'
import { userStore } from '@/stores/user'
import { message } from 'ant-design-vue'

const userState = userStore()
const appConfigState = AppConfigStore()
const router = useRouter()
const isLogin = ref(false)
const msg = ref('')
const im = RongIMLib.init({ appkey: 'tdrvipksty5k5' })
const messageList = ref([])
const joinList = reactive({
  data: {}
})

const chatRoomIdRef = ref('')
const messageContainer = ref(null)

if (userState?.token) {
  isLogin.value = true
} else {
  isLogin.value = false
}

const initRongIMLib = () => {
  getDQRongImLibToken()
    .then((val) => {
      RongIMLib.connect(val.data.url)
        .then((res) => {
          if (res.code === RongIMLib.ErrorCode.SUCCESS) {
            console.log('链接成功, 链接用户 id 为: ', res.data.userId)
            RongIMLib.joinExistChatRoom(chatRoomIdRef.value, {
              count: 50
            })
              .then((res) => {
                const { code, data } = res
                if (code === RongIMLib.ErrorCode.SUCCESS) {
                  console.log(code, data)
                } else {
                  console.log(code)
                }
              })
              .catch((error) => {
                console.log(error)
              })
          } else {
            console.warn('链接失败, code:', res.code)
          }
        })
        .catch((err) => {
          console.log(err)
        })
    })
    .catch((err) => {
      console.log(err, 'err')
    })
}

const Events = RongIMLib.Events

RongIMLib.addEventListener(Events.CONNECTING, () => {
  console.log('正在链接服务器')
})

RongIMLib.addEventListener(Events.DISCONNECT, () => {
  console.log('断开链接服务器')
})

RongIMLib.addEventListener(Events.SUSPEND, () => {
  console.log('断开链接服务器')
})

RongIMLib.addEventListener(Events.CONNECTED, () => {
  console.log('已经链接到服务器')
})

const listener = (evt) => {
  try {
    evt.messages.forEach((val) => {
      if (val.content.content) {
        const data = JSON.parse(val.content.content) ? JSON.parse(val.content.content) : null
        switch (data.type) {
          case 0:
            if (data.identity !== 3) {
              messageList.value.push(data)
              scrollToBottom()
            }
            break
          case 1:
            joinList.data = data
            break
        }
      }
    })
  } catch (error) {
    console.log(error, 'error')
  }
}

RongIMLib.addEventListener(Events.MESSAGES, listener)

const login = async () => {
  try {
    await appConfigState.LoginModalHandle(true)
    await userState.updateUserInfo()
    isLogin.value = true
  } catch (error) {
    console.error('登录失败', error)
  }
}

const sendMsg = () => {
  if (!userState.userInfo) return
  if (!msg.value) {
    message.error('请输入要发送的消息')
    return
  }
  const conversation = {
    conversationType: RongIMLib.ConversationType.CHATROOM,
    targetId: chatRoomIdRef.value
  }
  const data = {
    content: msg.value,
    contentColor: '',
    experienceLevel: 0,
    headUrl: undefined,
    id: '1816427620896739328',
    identity: 0,
    isLink: 0,
    nickname: userState?.userInfo?.nick ? userState?.userInfo?.nick : 'momo',
    nobleLevel: 0,
    pushTime: null,
    sign: '',
    type: 0,
    userId: 2170106,
    violationStatus: false
  }

  const messageIm = new RongIMLib.TextMessage({
    content: JSON.stringify(data)
  })

  RongIMLib.sendMessage(conversation, messageIm).then((res) => {
    if (res.code === RongIMLib.ErrorCode.SUCCESS) {
      console.log('消息发送成功', res.data)
      const data = JSON.parse(res.data.content.content)
        ? JSON.parse(res.data.content.content)
        : null
      switch (data.type?.toString()) {
        case '0':
          if (data.identity !== 3) {
            messageList.value.push(data)
          }
          break
        case '1':
          joinList.data = data
          break
      }
    } else {
      console.log('消息发送失败', res.code, res.msg)
    }
  })
  msg.value = ''
}

const listener2 = (event) => {
  if (event.rejoinedRoom) {
    console.log('SDK 内部重连聊天室信息:', event.rejoinedRoom)
  }
  if (event.updatedEntries) {
    console.log('监听到的聊天室 KV 更新:', event.updatedEntries)
  }
  if (event.userChange) {
    console.log('加入退出的用户通知:', event.userChange)
  }
  if (event.chatroomDestroyed) {
    console.log('聊天室销毁:', event.chatroomDestroyed)
  }
  if (event.chatroomNotifyMultiLoginSync) {
    console.log('加入退出多端同步通知:', event.chatroomNotifyMultiLoginSync)
  }
  if (event.chatroomNotifyBlock) {
    console.log('聊天室用户封禁通知:', event.chatroomNotifyBlock)
  }
  if (event.chatroomNotifyBan) {
    console.log('聊天室用户禁言通知:', event.chatroomNotifyBan)
  }
}

RongIMLib.addEventListener(Events.CHATROOM, listener2)

const scrollToBottom = () => {
  if (messageContainer.value) {
    nextTick(() => {
      messageContainer.value.scrollTop = messageContainer.value.scrollHeight
    })
  }
}

watch(
  () => userState?.token,
  (newValue) => {
    isLogin.value = !!newValue
  }
)

onMounted(() => {
  initRongIMLib()
})

const props = defineProps({
  chatId: {
    type: String,
    required: true
  }
})

watch(
  () => props.chatId,
  (newValue) => {
    chatRoomIdRef.value = newValue
    initRongIMLib()
  }
)
</script>

<style scoped lang="scss">
.right {
  width: 330px;
  height: 100%;
  background: #ffffff;
  border-radius: 10px;

  .live-stream {
    padding: 10px;
    border-radius: 10px;
    display: flex;
    flex-direction: column;
    position: relative;
    height: 100%;

    .tab {
      height: 44px;
      border-bottom: 1px solid #e2eeff;
      display: flex;
      align-items: center;
    }

    .live-button {
      width: 80px;
      height: 28px;
      background: #16b13a;
      border-radius: 20px 20px 20px 20px;
      margin: 0 auto;
      display: block;
      border: none;
      font-weight: 400;
      font-size: 14px;
      color: #ffffff;
    }

    .ranking-tabs {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 46px;

      span {
        margin: 0 10px;
        font-size: 16px;
        color: #666;
        cursor: pointer;

        &.active-tab {
          color: #000;
          font-weight: bold;
        }
      }
    }

    .ranking-list {
      .ranking-item {
        display: flex;
        align-items: center;
        padding: 5px;
        background: #fff4d8;
        border-radius: 10px;
        margin-bottom: 5px;
        font-size: 12px;
        color: #c28f1b;

        .ranking-badge {
          width: 30px;
          height: 30px;
          margin-right: 10px;
          object-fit: contain;
        }

        .player-name {
          flex: 1;
        }
      }
    }

    .activity {
      background-color: #e0f7e9;
      padding: 10px;
      border-radius: 10px;
      margin: 10px 0;
      font-size: 14px;
      color: #4caf50;
      display: flex;
      align-items: center;

      img {
        width: 20px;
      }

      .txt {
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
        font-size: 12px;
        margin-left: 5px;
      }
    }

    .message-container {
      flex: 1;
      overflow: scroll;
    }

    .vip-list {
      flex: 1;
      // overflow: scroll;

      .vip-item {
        margin-bottom: 5px;
        font-weight: 400;
        font-size: 12px;
        display: flex;
        align-items: flex-start;

        .nickname {
          color: #6e94ea;
          margin-right: 4px;
        }

        .vip-badge {
          width: 52px;
          margin-right: 10px;
          display: inline;
          object-fit: contain;
        }

        .vip-info {
          font-size: 12px;
          color: rgba(82, 90, 121, 1);
          word-break: break-all;
          word-wrap: break-word;
          line-height: 20px;
        }
      }
    }

    .join-list {
      padding: 10px 12px;
      display: flex;

      .nickname {
        color: rgba(110, 148, 234, 1);
        padding-right: 6px;
      }

      .text {
        color: rgb(155, 167, 189);
      }
    }

    .comment-section {
      .isNotLogin {
        flex: 1;
        height: 30px;
        padding: 0 10px;
        background: #f5f7ff;
        box-shadow: 0px 1px 0px 0px #f5f7ff;
        border-radius: 15px 15px 15px 15px;
        display: flex;
        align-items: center;
        font-weight: 400;
        font-size: 14px;

        .login_btn {
          margin-right: 6px;
          color: #67b6ff;
          cursor: pointer;
        }
      }

      .isLogin {
        display: flex;
        align-items: center;
        flex: 1;
      }

      .comment-input {
        display: flex;
        align-items: center;
        justify-content: space-between;
        width: 304px;
        height: 36px;
        background: #f5f7ff;
        border-radius: 20px 20px 20px 20px;

        input {
          flex: 1;
          border: none;
          padding: 5px 10px;
          border-radius: 20px;
          outline: none;
          background: transparent;
        }

        .send-button {
          background-color: #4caf50;
          color: white;
          border: none;
          border-radius: 0 20px 20px 0;
          padding: 5px 15px;
          cursor: pointer;
        }
      }
    }
  }
}
</style>
